package cn.edu.xmu.oomall.order.controller;

import cn.edu.xmu.oomall.core.util.Common;
import cn.edu.xmu.oomall.core.util.ReturnNo;
import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.oomall.order.microservice.PrivilegeService;
import cn.edu.xmu.oomall.order.microservice.vo.FreightCalculatingPostVo;
import cn.edu.xmu.oomall.order.microservice.vo.QuantityVo;
import cn.edu.xmu.oomall.order.model.bo.Order;
import cn.edu.xmu.oomall.order.model.bo.OrderItem;
import cn.edu.xmu.oomall.order.model.bo.Payment;
import cn.edu.xmu.oomall.order.model.po.OrderItemPo;
import cn.edu.xmu.oomall.order.model.po.OrderPo;
import cn.edu.xmu.oomall.order.model.po.OrderPoExample;
import cn.edu.xmu.oomall.order.model.vo.*;
import cn.edu.xmu.oomall.order.service.OrderService;
import cn.edu.xmu.oomall.order.util.ValidList;
import cn.edu.xmu.privilegegateway.annotation.aop.Audit;
import cn.edu.xmu.privilegegateway.annotation.aop.LoginName;
import cn.edu.xmu.privilegegateway.annotation.aop.LoginUser;
import cn.edu.xmu.privilegegateway.annotation.util.InternalReturnObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;

@Api(value = "订单", tags = "order")
@RestController
@RefreshScope
@RequestMapping(value = "/", produces = "application/json;charset=UTF-8")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private HttpServletResponse httpServletResponse;

//    /**
//     * 查询自己订单的支付信息
//     * @param id
//     * @return Object
//     */
//    @Audit
//    @GetMapping("orders/{id}/payment")
//    public Object getOrderPayments(@PathVariable Long id) {
//        return Common.decorateReturnObject(orderService.getOrderPayments(id));
//    }


    /**
     * 获得订单的所有状态
     */
    @GetMapping("/orders/states")
    public Object getOrderStates() {
        ReturnObject ret = orderService.getOrderState();
        return Common.decorateReturnObject(ret);
    }

    /**
     * 买家查询名下订单(概要)
     */
    @Audit
    @GetMapping("/orders")
    public Object selectSimpleOrder(@LoginUser Long userId,
                                    @RequestParam(name = "orderSn", required = false) String orderSn,
                                    @RequestParam(name = "state", required = false) Integer state,
                                    @RequestParam(name = "beginTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime beginTime,
                                    @RequestParam(name = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime endTime,
                                    @RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        System.out.println(userId);
        ReturnObject ret = orderService.selectSimpleOrder(userId, orderSn, state, beginTime, endTime, page, pageSize);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 买家申请建立订单
     */
    @Audit
    @PostMapping("/orders")
    public Object insertOrder(@RequestBody OrderVo orderVo, @LoginUser Long userId, @LoginName String userName, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Common.decorateReturnObject(new ReturnObject(ReturnNo.FIELD_NOTVALID, "传入的RequestBody参数格式不合法"));
        }
        try {
            ReturnObject ret = orderService.insertOrder(orderVo, userId, userName);
            if (ret.getCode().equals(ReturnNo.OK)) {
                httpServletResponse.setStatus(201);
            }
            return Common.decorateReturnObject(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnObject<>();
    }

    /**
     * 买家查询订单完整信息（普通，团购，预售）
     */
    @Audit
    @GetMapping("/orders/{id}")
    public Object selectOrderInfo(@LoginUser Long userId, @PathVariable Long id) {
        ReturnObject ret = orderService.selectOrderInfo(id, userId);
        return Common.decorateReturnObject(ret);
    }


    /**
     * 买家修改本人名下订单
     */
    @Audit
    @PutMapping("/orders/{id}")
    public Object updateOrder(@PathVariable Long id, @Validated @RequestBody OrderSimpleVo orderSimpleVo,
                              @LoginUser Long userId, @LoginName String userName, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return Common.decorateReturnObject(new ReturnObject(ReturnNo.FIELD_NOTVALID, "传入的RequestBody参数格式不合法"));
        }
        ReturnObject ret = orderService.updateOrder(id, orderSimpleVo, userId, userName, bindingResult);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 买家逻辑删除本人名下订单
     */
    @Audit
    @DeleteMapping("/orders/{id}")
    public Object deleteOrder(@PathVariable Long id,
                              @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.deleteOrder(id, userId, userName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 买家取消本人名下订单
     */
    @Audit
    @PutMapping("/orders/{id}/cancel")
    public Object cancelOrder(@PathVariable Long id, @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.cancelOrder(id, userId, userName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 买家标记确认收货
     */
    @Audit
    @PutMapping("/orders/{id}/confirm")
    public Object confirmOrder(@PathVariable Long id, @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.confirmOrder(id, userId, userName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 买家查看支付单
     */
    @Audit
    @GetMapping("/orders/{id}/payment")
    public Object checkOrderPayment(@PathVariable Long id, @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.checkOrderPayment(id, userId, userName);
        return Common.decorateReturnObject(ret);
    }

//=================================== 店家 ====================================

    /**
     * 店家查询商户所有订单 (概要)
     */
    @Audit
    @GetMapping("shops/{shopId}/orders")
    public Object selectSimpleOrder(@LoginUser Long userId,
                                    @PathVariable Long shopId,
                                    @RequestParam(name = "customerId", required = false) Long customerId,
                                    @RequestParam(name = "orderSn", required = false) String orderSn,
                                    @RequestParam(name = "beginTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime beginTime,
                                    @RequestParam(name = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime endTime,
                                    @RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        ReturnObject ret = orderService.selectSimpleOrder(shopId, customerId, orderSn, beginTime, endTime, page, pageSize);
        return Common.decorateReturnObject(ret);
    }


    /**
     * 店家修改订单 (留言)
     */
    @Audit
    @PutMapping("shops/{shopId}/orders/{id}")
    public Object updateOrder(@PathVariable Long shopId, @PathVariable Long id, @Validated @RequestBody OrderMessageVo orderMessageVo, @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.updateOrder(shopId, id, orderMessageVo, userId, userName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 店家查询店内订单完整信息（普通，团购，预售）
     */
    @Audit
    @GetMapping("shops/{shopId}/orders/{id}")
    public Object selectOrderInfo(@PathVariable Long shopId, @PathVariable Long id, @LoginUser Long userId) {
        ReturnObject ret = orderService.selectOrderInfo(shopId, id, userId);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 店家对订单标记发货
     */
    @Audit
    @PutMapping("shops/{shopId}/orders/{id}/deliver")
    public Object confirmOrder(@PathVariable Long shopId, @PathVariable Long id, @RequestBody OrderShipmentSnVo orderShipmentSnVo, @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.confirmOrder(shopId, id, orderShipmentSnVo, userId, userName);
        return Common.decorateReturnObject(ret);
    }

//=============================  gf  ==========================================================


    /**
     * 管理员创建售后订单
     *
     * @param shopId 商铺id
     * @param userId
     * @param userName
     * @param afterSaleOrderVo
     * @param bindingResult
     * @param request
     * @return
     */
    @Audit
    @PostMapping("internal/shops/{shopId}/orders")
    public Object createVirtualOrder(@PathVariable long shopId, @LoginUser long userId, @LoginName String userName,
                                     @RequestBody AfterSaleOrderVo afterSaleOrderVo, BindingResult bindingResult,
                                     HttpServletRequest request) {

        return Common.decorateReturnObject(orderService.createVirtualOrder(afterSaleOrderVo, shopId, userId, userName, bindingResult));
    }


    /**
     * 取消订单
     *
     * @param shopId
     * @param id
     * @param userName
     * @param userId
     * @return
     */
    @Audit
    @PutMapping("internal/shops/{shopId}/orders/{id}/cancel")
    public Object cancelOrder(@PathVariable long shopId, @PathVariable long id,
                              @LoginName String userName, @LoginUser long userId) {

        return Common.decorateReturnObject(orderService.cancelOrderByAdmin(shopId, id));

    }

    /**
     * 确认团购
     *
     * @param shopId
     * @param id
     * @param userId
     * @param userName
     * @return
     */
    @Audit
    @PutMapping("internal/shops/{shopId}/grouponorders/{id}/confirm")
    public Object confirmGrouponOrder(@PathVariable long shopId, @PathVariable long id,
                                      @LoginUser long userId, @LoginName String userName) {
        return Common.decorateReturnObject(orderService.confirmGrouponOrder(shopId, id));
    }


    /**
     * 查询退款信息
     */
    @Audit
    @GetMapping("orders/{id}/refund")
    public Object selectRefund(@PathVariable Long id, @LoginUser Long userId, @LoginName String userName) {
        ReturnObject ret = orderService.selectRefund(id, userId, userName);
        return Common.decorateReturnObject(ret);
    }
}
